import attr from './attr.js'

export function replaceTextWithT(code) {
  const parser = new DOMParser();
  const doc = parser.parseFromString(code, 'text/html');
  const elements = doc.body.children;
	const obj = {}
	elements.forEach(element => {
		getTextWithName(element, obj);
	})
  return element.outerHTML;
}

function getTextWithName(element, obj = {}) {
  const textNodes = getTextNodes(element);
  textNodes.forEach(node => {
    const parentClass = node.parentNode.getAttribute('class');
		let name = ''
		attr.forEach(v => {
			if (v.reg.test(parentClass)) {
				name = v.name
			}
		})
		const text = node.textContent;
		if(name) obj[name] = text
  });
}

function getTextNodes(element) {
  let textNodes = [];
  for (let node of element.childNodes) {
    if (node.nodeType === Node.TEXT_NODE) {
      textNodes.push(node);
    } else {
      textNodes = textNodes.concat(getTextNodes(node));
    }
  }
  return textNodes;
}